package util

import (
	"encoding/json"
	"gopkg.in/yaml.v3"
	"io"
	v12 "k8s.io/api/apps/v1"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

// ConvertYamlToPodSpec kubernetes struct只写了json tag,所以需要先转换成json数组才能转换成struct
func ConvertYamlToPodSpec(data map[string]interface{}) (*v1.PodSpec, error) {
	yamlData, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	res := new(v1.PodSpec)

	mapData := make(map[string]interface{})
	err = yaml.Unmarshal(yamlData, &mapData)
	if err != nil {
		return nil, err
	}

	jsonData, err := json.Marshal(mapData)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(jsonData, res)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func WriteStruct(data runtime.Object, w io.Writer) (n int, err error) {
	switch obj := data.(type) {
	case *v12.Deployment:
		obj.Kind = "Deployment"
		obj.APIVersion = "apps/v1"
	case *v1.Service:
		obj.Kind = "Service"
		obj.APIVersion = "v1"
	case *v1.Pod:
		obj.Kind = "Pod"
		obj.APIVersion = "v1"
	case *v1.PersistentVolume:
		obj.Kind = "PersistentVolume"
		obj.APIVersion = "v1"
	case *v1.PersistentVolumeClaim:
		obj.Kind = "PersistentVolumeClaim"
		obj.APIVersion = "v1"
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		return 0, err
	}

	m := make(map[string]interface{})
	err = json.Unmarshal(jsonData, &m)
	if err != nil {
		return 0, err
	}
	delete(m, "status")

	yamlData, err := yaml.Marshal(m)
	if err != nil {
		return 0, err
	}

	write, err := w.Write(yamlData)
	if err != nil {
		return 0, err
	}

	return write, nil
}

func CopySpec(in, out *v1.PodSpec) {
	temp := new(v1.PodSpec)
	out.DeepCopyInto(temp)

	in.DeepCopyInto(out)

	for index, i := range temp.Containers {
		if out.Containers[index].Name == "" {
			out.Containers[index].Name = i.Name
		}
		if out.Containers[index].Image == "" {
			out.Containers[index].Image = i.Image
		}
		if len(out.Containers[index].Ports) == 0 {
			out.Containers[index].Ports = i.Ports
		}

	}
}
